<template>
  <div style="height: 6vh;background-color:#fff;padding: 0 20px 10px;">
    <span style="line-height:60px;font-size:20px;">新增围栏</span>
    <el-button type="primary" style="float:right;margin-top:12px;" @click="router.push('/geofence')">返回</el-button>
  </div>
  <div id="mapContainer" style="width: 100%; height: 81vh;"></div>
  <el-dialog title="围栏信息" v-model="dialogVisible">
    <el-form>
      <el-form-item label="围栏名称">
        <el-input placeholder="请输入围栏名称" v-model="geofence.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="saveGeofence">确定</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import router from '@/router';
import { nextTick, onMounted, ref } from 'vue';
import { DrawScene, DrawControl,OperateEventType } from 'bmap-draw';
import qs from "qs";
import axios from 'axios';
import { ElMessage } from 'element-plus';

const geofence = ref({
  name: '',
  position: {}
});
const dialogVisible = ref(false);
var map;
onMounted(() => { 
  nextTick(() => {
    map = new BMapGL.Map('mapContainer');
    map.centerAndZoom(new BMapGL.Point(118.700, 32.159), 15);
    map.enableScrollWheelZoom(true);
    const scene = new DrawScene(map);
    const drawContrl = new DrawControl(scene,{
      enableTips: false,
      anchor: BMAP_ANCHOR_TOP_RIGHT,
      drawingItems: [
         'circle',
         'rectangle'
       ]
    });
    scene.addEventListener(OperateEventType.COMPLETE, (event) => {
      dialogVisible.value = true;
      let overlay = event.target.overlay;
      if (overlay instanceof BMapGL.Circle) {
         geofence.value.position.type = 'circle';
         geofence.value.position.longitude = overlay.getCenter().lng;
         geofence.value.position.latitude = overlay.getCenter().lat;
         geofence.value.position.radius = overlay.getRadius();
       } else {
         geofence.value.position.type = 'rectangle';
         let recPoints = [];
         for (let i = 0; i < 4; i++){
           recPoints.push(overlay.points[i].latLng.lng + '-' + overlay.points[i].latLng.lat);
         }
         geofence.value.position.recPoints = recPoints.join(',');
       }
    });
    map.addControl(drawContrl);
  });
});
const saveGeofence = () => {
  if(!geofence.value.name || geofence.value.name.trim()==''){
    ElMessage.warning('请输入围栏名称！');
    return;
  }
  geofence.value.position = JSON.stringify(geofence.value.position);
  let data = qs.stringify(geofence.value);
  axios.post(BASE_URL + '/v1/geofence/save', data).then(response => {
    if (response.data.code == 2000) {
      ElMessage.success("保存成功！");
      dialogVisible.value = false;
      router.push('/geofence');
    } else {
      ElMessage.error(response.data.msg);
    }
  })
};
const handleClose = () => {
  dialogVisible.value = false;
  geofence.value = {name: '',points: {}};
  map.clearOverlays();
};
</script>

<style scoped>

</style>